'''
Created on Dec 16, 2010

@author: mwicat
'''

import logging
logger = logging.getLogger(__name__)

import SocketServer

from sniffylib.core import services
from sniffylib.util import threads

from threading import Thread

import core, shell

from SocketServer import *

ThreadingMixIn.daemon_threads = True
SocketServer.allow_reuse_address = True


class MyTCPHandler(StreamRequestHandler):

    def handle(self):
        src = self.client_address[0]
        while True:
            msg = self.rfile.readline().strip()
            logger.debug('read: %s' % msg)
            self.server.handle_cmd(msg, src)


class SocketService(core.BaseRPCService):
    
    def __init__(self, shell, addr):
        core.BaseRPCService.__init__(self, shell)
        self.addr = addr
        self.server = None
        self.server_service = None

    def handle(self, msg, src):
        name, params = core.parse_cmdln(msg)
        cmd = core.SniffyCmd(src, name, params)
        self.dispatch_cmd(cmd)
    
    def start_service(self):
        self.server = ThreadingTCPServer(self.addr, MyTCPHandler)
        self.server.handle_cmd = self.handle
        self.server_service = threads.BgService(self.server.handle_request)
        self.server_service.start()

    def stop_service(self):
        self.server.server_close()
        self.server_service.stop()
        self.server = None
